package com.nuoniu.sibanyun.controller.system;

import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.SendSms;
import com.nuoniu.sibanyun.entity.SysUser;
import com.nuoniu.sibanyun.service.ISendSmsService;
import com.nuoniu.sibanyun.service.ISysCompanyService;
import com.nuoniu.sibanyun.service.ISysUserService;
import com.nuoniu.sibanyun.common.result.HttpResult;
import com.nuoniu.sibanyun.service.app.IAppInfoService;
import com.nuoniu.sibanyun.service.redis.RedisService;
import com.nuoniu.sibanyun.utils.IpUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户注册登录找回相关接口
 * @author 小啊刚
 * @date 2020/6/11
 */
@RestController
@RequestMapping("/auth")
@Api(value="用户注册",tags={"用户注册登录找回相关接口","APP_用户注册相关"})
public class AuthController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ISendSmsService sendSmsService;
    @Autowired
    private IAppInfoService appInfoService;

    /**
     * 用户注册
     * @author 小啊刚
     * @date 2020/6/10
     */
    @PostMapping("/user/register")
    @ApiOperation(value = "用户注册" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userPhone", value = "手机号码"),
            @ApiImplicitParam(name = "realName", value = "用户姓名"),
            @ApiImplicitParam(name = "password", value = "登录密码"),
            @ApiImplicitParam(name = "userType", value = "注册类型1:单位2:个人"),
            @ApiImplicitParam(name = "vCode", value = "手机验证码"),
            @ApiImplicitParam(name = "companyName", value = "单位名称"),
            @ApiImplicitParam(name = "email", value = "邮箱"),
            @ApiImplicitParam(name = "shareCode", value = "推荐码"),
            @ApiImplicitParam(name = "sharePhone", value = "推荐人手机号"),
    })
    public HttpResult registerUser(@RequestBody Map<String, String> registerUser){
        if(StringUtils.isEmpty(registerUser.get("userPhone"))){
           throw new NuoNiuException("手机号码不能为空");
        }

        if(StringUtils.isEmpty(registerUser.get("realName"))) {
           throw new NuoNiuException("用户姓名不能为空");
        }

        if(StringUtils.isEmpty(registerUser.get("password"))) {
           throw new NuoNiuException("登录密码不能为空");
        }

        if(registerUser.get("userType").equals("1") && StringUtils.isEmpty(registerUser.get("companyName"))) {
           throw new NuoNiuException("单位名称不能空");
        }

        //注册
        return sysUserService.registerUser(registerUser);
    }

    @Autowired
    private ISysCompanyService companyService;

    /**
     * 用户入职注册
     * @author 小啊刚
     * @date 2020-08-04
     */
    @PostMapping("/user/entryRegister")
    @ApiOperation(value = "用户入职注册" )
    public HttpResult entryRegister(@RequestBody Map<String, String> registerUser){
        if(StringUtils.isEmpty(registerUser.get("userPhone"))){
           throw new NuoNiuException("手机号码不能为空");
        }

        SysUser user = sysUserService.findByUserName(registerUser.get("userPhone"));
        if(user != null && user.getCompanyId() != null) {
            throw new NuoNiuException("该手机号已入职");
        }else {
            if(StringUtils.isEmpty(registerUser.get("realName"))) {
               throw new NuoNiuException("用户姓名不能为空");
            }

            if(StringUtils.isEmpty(registerUser.get("password"))) {
               throw new NuoNiuException("登录密码不能为空");
            }

            if(StringUtils.isEmpty(registerUser.get("companyName"))) {
               throw new NuoNiuException("单位名称不能空");
            }
        }

        //注册
        return sysUserService.entryRegister(registerUser);
    }

    /**
     * 发送注册验证码
     * @author 小啊刚
     * @date 2020/6/10
     */
    @GetMapping("/user/sendUserCode")
    @ApiOperation(value = "发送注册验证码" )
    @ApiImplicitParams({
            @ApiImplicitParam(name="userPhone",value="用户电话",required=true,paramType="query"),
            @ApiImplicitParam(name="imgCode",value="图片验证码",required=true,paramType="query"),
    })
    public HttpResult sendUserCode(String userPhone, String imgCode, HttpServletRequest request) {
        String ip = IpUtil.getClientIp(request);
        String regex = "^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
        if(StringUtils.isEmpty(userPhone) || userPhone.length() != 11) {
            throw new NuoNiuException("手机号格式不正确");
        }

        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(userPhone);
        boolean isMatch = m.matches();
        if(!isMatch) {
            throw new NuoNiuException("手机号格式不正确");
        }

        if(StringUtils.isBlank(imgCode)) {
            throw new NuoNiuException("图片验证码不能为空");
        }

        Object code = redisService.get("register_" + userPhone + "_" + ip);
        if(code == null || !(code.toString().toLowerCase().equals(imgCode.toLowerCase()))) {
            throw new NuoNiuException("图片验证码不正确");
        }

        SysUser sysUser = sysUserService.getUserByPhone(userPhone);
        if(sysUser != null) {
            throw new NuoNiuException("手机号已注册");
        }

        if(redisService.hasKey("check_" + userPhone)) {
            throw new NuoNiuException("请勿频繁发送验证码");
        }

        List<SendSms> sendSmsList = sendSmsService.getSendSmsList(userPhone);
        if(sendSmsList.size() >= 5) {
            throw new NuoNiuException("今天发送次数已上限");
        }
        //发送验证码
        return HttpResult.ok(sysUserService.sendUserCode(userPhone, "用户注册"));
    }

    /**
     * 发送忘记密码手机验证码
     * @author 小啊刚
     * @date 2020-08-03
     */
    @GetMapping("/user/sendForgetPwdCode")
    @ApiOperation(value = "发送忘记密码手机验证码" )
    @ApiImplicitParams({
            @ApiImplicitParam(name="userPhone",value="用户电话",required=true,paramType="query"),
            @ApiImplicitParam(name="imgCode",value="图片验证码",required=true,paramType="query"),
    })
    public HttpResult sendForgetPwdCode(String userPhone, String imgCode, HttpServletRequest request) {
        String ip = IpUtil.getClientIp(request);
        String regex = "^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
        if(StringUtils.isEmpty(userPhone) || userPhone.length() != 11) {
            throw new NuoNiuException("手机号格式不正确");
        }

        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(userPhone);
        boolean isMatch = m.matches();
        if(!isMatch) {
            throw new NuoNiuException("手机号格式不正确");
        }

        Object code = redisService.get("forget_pwd_" + ip);
        if(code == null || !(code.toString().toLowerCase().equals(imgCode.toLowerCase()))) {
            throw new NuoNiuException("图片验证码不正确");
        }

        SysUser sysUser = sysUserService.getUserByPhone(userPhone);
        if(sysUser == null) {
            throw new NuoNiuException("手机号未注册");
        }

        if(redisService.hasKey("check_" + userPhone)) {
            throw new NuoNiuException("请勿频繁发送验证码");
        }

        List<SendSms> sendSmsList = sendSmsService.getSendSmsList(userPhone);
        if(sendSmsList.size() >= 5) {
            throw new NuoNiuException("今天发送次数已上限");
        }
        //发送验证码
        return HttpResult.ok(sysUserService.sendUserCode(userPhone, "用户修改密码"));
    }

    /**
     * 发送入职注册手机验证码
     * @author 小啊刚
     * @date 2020-08-03
     */
    @GetMapping("/user/sendEntryCode")
    @ApiOperation(value = "发送入职注册手机验证码" )
    @ApiImplicitParams({
            @ApiImplicitParam(name="userPhone",value="用户电话",required=true,paramType="query"),
            @ApiImplicitParam(name="imgCode",value="图片验证码",required=true,paramType="query"),
    })
    public HttpResult sendEntryCode(String userPhone, String imgCode, HttpServletRequest request) {
        String ip = IpUtil.getClientIp(request);
        String regex = "^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
        if(StringUtils.isEmpty(userPhone) || userPhone.length() != 11) {
            throw new NuoNiuException("手机号格式不正确");
        }

        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(userPhone);
        boolean isMatch = m.matches();
        if(!isMatch) {
            throw new NuoNiuException("手机号格式不正确");
        }

        Object code = redisService.get("register_" + userPhone + "_" + ip);
        if(code == null || !(code.toString().toLowerCase().equals(imgCode.toLowerCase()))) {
            throw new NuoNiuException("图片验证码不正确");
        }

        SysUser sysUser = sysUserService.getUserByPhone(userPhone);
        if(sysUser != null && sysUser.getCompanyId() != null) {
            throw new NuoNiuException("你已入职");
        }

        if(redisService.hasKey("check_" + userPhone)) {
            throw new NuoNiuException("请勿频繁发送验证码");
        }

        List<SendSms> sendSmsList = sendSmsService.getSendSmsList(userPhone);
        if(sendSmsList.size() >= 5) {
            throw new NuoNiuException("今天发送次数已上限");
        }

        //发送验证码
        return HttpResult.ok(sysUserService.sendUserCode(userPhone, "用户修改密码"));
    }

    /**
     * 校验用户
     * @author 小啊刚
     * @date 2020/6/10
     */
    @GetMapping("/user/checkUser")
    @ApiOperation(value = "校验用户" )
    @ApiImplicitParams({
            @ApiImplicitParam(name="userPhone",value="用户电话",required=true,paramType="query"),
            @ApiImplicitParam(name="userName",value="姓名",paramType="query"),
            @ApiImplicitParam(name="email",value="邮箱",required=true,paramType="query"),
            @ApiImplicitParam(name="code",value="图片验证码",required=true,paramType="query"),
            @ApiImplicitParam(name="companyName",value="公司名称",paramType="query"),
    })
    public HttpResult checkUser(String userPhone, String userName, String email, String companyName, String code) {
        if(StringUtils.isNotBlank(code)) {
            Object rCode = redisService.get("sms_" + userPhone);
            if(rCode != null && rCode.equals(code)) {
                return HttpResult.ok();
            }else {
                throw new NuoNiuException("验证码不正确");
            }
        }
        return sysUserService.checkUser(userPhone, userName, email, companyName);
    }

    /**
     * 校验入职手机号
     * @author 小啊刚
     * @date 2020-08-04
     */
    @GetMapping("/entry/checkUserPhone")
    @ApiOperation(value = "校验入职手机号" )
    @ApiImplicitParams({
            @ApiImplicitParam(name="userPhone",value="用户电话",required=true,paramType="query"),
    })
    public HttpResult checkUserPhone(String userPhone) {
        if(StringUtils.isEmpty(userPhone) || userPhone.length() != 11) {
            throw new NuoNiuException("手机号格式不正确");
        }

        SysUser sysUser = sysUserService.getUserByPhone(userPhone);
        if(sysUser != null) {
            if(sysUser.getCompanyId() != null) {
                throw new NuoNiuException("你已入职");
            }else {
                return HttpResult.ok("你已注册", sysUser);
            }
        }
        return HttpResult.ok("未注册", "0");
    }

    /**
     * 用户重置密码
     * @author 小啊刚
     * @date 2020-08-03
     */
    @PostMapping("/user/resetPwd")
    @ApiOperation(value = "用户重置密码", notes = "一个三个参数，都不能为空：userPhone:手机号,password:登录密码,vCode:手机验证码")
    public HttpResult resetPwd(@RequestBody Map<String, String> userInfo) {
        if(StringUtils.isEmpty(userInfo.get("userPhone"))) {
            throw new NuoNiuException("手机号不能为空");
        }
        if(StringUtils.isEmpty(userInfo.get("password"))) {
           throw new NuoNiuException("登录密码不能为空");
        }
        if(StringUtils.isEmpty(userInfo.get("vCode"))) {
           throw new NuoNiuException("手机验证码不能为空");
        }
        //重置密码
        return sysUserService.resetPwd(userInfo);
    }

    /**
     * 获取入职公司信息
     * @author 小啊刚
     * @date 2020-08-03
     */
    @GetMapping("/user/getEntryCompany")
    @ApiOperation(value = "获取入职公司信息" )
    @ApiImplicitParams({
            @ApiImplicitParam(name="cId",value="公司ID",required=true,paramType="query"),
            @ApiImplicitParam(name="code",value="公司Code",required=true,paramType="query")
    })
    public HttpResult getEntryCompany(String cId, String code) {
        return HttpResult.ok(companyService.getEntryCompany(cId, code));
    }

    /**
     * 邀请注册跳转
     * @author 小啊刚
     * @date 2021-07-28
     */
    @ApiOperation("邀请注册跳转")
    @GetMapping("userEntry")
    public String userEntry() {
        return "redirect:https://www.sibanyun.com/user/userEntry?cId=2&code=AAAAAA";
    }

    @ApiOperation("短信邀请员工注册")
    @GetMapping("smsRegister")
    public HttpResult smsRegister(Integer empId, String vCode) {
        if(empId == null) {
            throw new NuoNiuException("员工id不能为空");
        }

        sysUserService.smsRegister(empId, vCode);
        return HttpResult.ok();
    }

    /**
     * 获取最新下载地址
     * @author 小啊刚
     * @date 2021-09-09
     */
    @ApiOperation("获取最新下载地址")
    @GetMapping("getDownloadUrl")
    @ApiImplicitParams({
         @ApiImplicitParam(name="type",value="类型1:安卓 2:ios",required=true,paramType="query")
    })
    public HttpResult getDownloadUrl(Integer type) {
        return HttpResult.ok(appInfoService.getNewestApp(type));
    }

}

